package controllers

import (
	"encoding/json"
	"strconv"
	"supershare/backend/models"
	"supershare/backend/utils"
	"time"

	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

// CouponController 优惠券管理控制器
type CouponController struct {
	web.Controller
}

// CouponListRequest 优惠券列表请求参数
type CouponListRequest struct {
	Page           int    `json:"page" form:"page"`
	PageSize       int    `json:"pageSize" form:"pageSize"`
	Name           string `json:"name" form:"name"`
	Code           string `json:"code" form:"code"`
	Type           int8   `json:"type" form:"type"`
	Status         int8   `json:"status" form:"status"`
	ApplicableType int8   `json:"applicable_type" form:"applicable_type"`
}

// CouponCreateRequest 创建优惠券请求参数
type CouponCreateRequest struct {
	Name              string  `json:"name"`
	Code              string  `json:"code"`
	Type              int8    `json:"type"`
	Value             float64 `json:"value"`
	MinConsume        float64 `json:"min_consume"`
	ValidDays         int     `json:"valid_days"`
	StartTime         int64   `json:"start_time"`
	EndTime           int64   `json:"end_time"`
	TotalCount        int     `json:"total_count"`
	PerLimit          int     `json:"per_limit"`
	Description       string  `json:"description"`
	UseRules          string  `json:"use_rules"`
	Status            int8    `json:"status"`
	ApplicableType    int8    `json:"applicable_type"`
	ApplicableIds     string  `json:"applicable_ids"`
	AvailableWeekdays string  `json:"available_weekdays"`
	AvailableTimes    string  `json:"available_times"`
	Discount          float64 `json:"discount"`
	Duration          int     `json:"duration"`
}

// CouponUpdateRequest 更新优惠券请求参数
type CouponUpdateRequest struct {
	Name              string  `json:"name"`
	Code              string  `json:"code"`
	Type              int8    `json:"type"`
	Value             float64 `json:"value"`
	MinConsume        float64 `json:"min_consume"`
	ValidDays         int     `json:"valid_days"`
	StartTime         int64   `json:"start_time"`
	EndTime           int64   `json:"end_time"`
	TotalCount        int     `json:"total_count"`
	PerLimit          int     `json:"per_limit"`
	Description       string  `json:"description"`
	UseRules          string  `json:"use_rules"`
	Status            int8    `json:"status"`
	ApplicableType    int8    `json:"applicable_type"`
	ApplicableIds     string  `json:"applicable_ids"`
	AvailableWeekdays string  `json:"available_weekdays"`
	AvailableTimes    string  `json:"available_times"`
	Discount          float64 `json:"discount"`
	Duration          int     `json:"duration"`
}

// List 获取优惠券列表
func (c *CouponController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取请求参数
	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	name := c.GetString("name")
	code := c.GetString("code")
	type_, _ := c.GetInt8("type", -1)
	status, _ := c.GetInt8("status", -1)
	applicableType, _ := c.GetInt8("applicable_type", -1)

	// 构建过滤条件
	filters := make(map[string]interface{})
	if name != "" {
		filters["name"] = name
	}
	if code != "" {
		filters["code"] = code
	}
	if type_ >= 0 {
		filters["type"] = type_
	}
	if status >= 0 {
		filters["status"] = status
	}
	if applicableType >= 0 {
		filters["applicable_type"] = applicableType
	}

	// 加盟商只能查看自己的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 查询优惠券列表
	coupons, total, err := models.GetCouponList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取优惠券列表成功",
		"data": map[string]interface{}{
			"list":  coupons,
			"total": total,
		},
	}
	c.ServeJSON()
}

// GetOne 获取单个优惠券详情
func (c *CouponController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取优惠券ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的优惠券ID",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠券信息
	coupon, err := models.GetCouponById(id)
	if err != nil || coupon == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "优惠券不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 检查加盟商权限
	if permResult.Admin.FranchiseId > 0 && coupon.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权访问此优惠券",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取优惠券信息成功",
		"data":    coupon,
	}
	c.ServeJSON()
}

// Create 创建优惠券
func (c *CouponController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req CouponCreateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数" + err.Error(),
		}
		c.ServeJSON()
		return
	}

	if req.Code == "" {
		req.Code = utils.GenerateCouponCode("CC", 16)
	}

	// 创建优惠券
	coupon := &models.Coupon{
		Name:              req.Name,
		Code:              req.Code,
		Type:              req.Type,
		Value:             req.Value,
		MinConsume:        req.MinConsume,
		ValidDays:         req.ValidDays,
		StartTime:         req.StartTime,
		EndTime:           req.EndTime,
		TotalCount:        req.TotalCount,
		PerLimit:          req.PerLimit,
		Description:       req.Description,
		UseRules:          req.UseRules,
		Status:            req.Status,
		ApplicableType:    req.ApplicableType,
		ApplicableIds:     req.ApplicableIds,
		AvailableWeekdays: req.AvailableWeekdays,
		AvailableTimes:    req.AvailableTimes,
		Discount:          req.Discount,
		Duration:          req.Duration,
	}

	// 设置加盟商ID
	coupon.FranchiseId = permResult.Admin.FranchiseId

	// 设置创建者信息
	coupon.CreatedBy = permResult.Admin.Username
	coupon.UpdatedBy = permResult.Admin.Username
	coupon.CreatedAt = time.Now().Unix()
	coupon.UpdatedAt = coupon.CreatedAt

	// 保存到数据库
	id, err := models.CreateCoupon(coupon)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建优惠券失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建优惠券成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// Update 更新优惠券
func (c *CouponController) Update() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取优惠券ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的优惠券ID",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠券信息
	coupon, err := models.GetCouponById(id)
	if err != nil || coupon == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "优惠券不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 检查加盟商权限
	if permResult.Admin.FranchiseId > 0 && coupon.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权修改此优惠券",
		}
		c.ServeJSON()
		return
	}

	// 解析请求参数
	var req CouponUpdateRequest
	err = json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		logs.Error("CouponController.Update: %v", err)
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 更新优惠券信息
	coupon.Name = req.Name
	coupon.Code = req.Code
	coupon.Type = req.Type
	coupon.Value = req.Value
	coupon.MinConsume = req.MinConsume
	coupon.ValidDays = req.ValidDays
	coupon.StartTime = req.StartTime
	coupon.EndTime = req.EndTime
	coupon.TotalCount = req.TotalCount
	coupon.PerLimit = req.PerLimit
	coupon.Description = req.Description
	coupon.UseRules = req.UseRules
	coupon.Status = req.Status
	coupon.ApplicableType = req.ApplicableType
	coupon.ApplicableIds = req.ApplicableIds
	coupon.AvailableWeekdays = req.AvailableWeekdays
	coupon.AvailableTimes = req.AvailableTimes
	coupon.Discount = req.Discount
	coupon.Duration = req.Duration

	// 更新者信息
	coupon.UpdatedBy = permResult.Admin.Username
	coupon.UpdatedAt = time.Now().Unix()

	// 保存到数据库
	err = models.UpdateCoupon(coupon)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "更新优惠券失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "更新优惠券成功",
	}
	c.ServeJSON()
}

// Delete 删除优惠券
func (c *CouponController) Delete() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取优惠券ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的优惠券ID",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠券信息
	coupon, err := models.GetCouponById(id)
	if err != nil || coupon == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "优惠券不存在或获取信息失败",
		}
		c.ServeJSON()
		return
	}

	// 检查加盟商权限
	if permResult.Admin.FranchiseId > 0 && coupon.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权删除此优惠券",
		}
		c.ServeJSON()
		return
	}

	// 删除优惠券
	err = models.DeleteCoupon(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "删除优惠券失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "删除优惠券成功",
	}
	c.ServeJSON()
}

// GetMyCoupons 获取我的优惠券列表
func (c *CouponController) GetMyCoupons() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取请求参数
	userId, _ := strconv.ParseInt(c.GetString("user_id"), 10, 64)
	if userId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的用户ID",
		}
		c.ServeJSON()
		return
	}

	page, _ := strconv.Atoi(c.GetString("page"))
	if page <= 0 {
		page = 1
	}

	pageSize, _ := strconv.Atoi(c.GetString("pageSize"))
	if pageSize <= 0 || pageSize > 100 {
		pageSize = 10
	}

	status, _ := c.GetInt8("status", -1)

	// 构建过滤条件
	filters := make(map[string]interface{})
	filters["user_id"] = userId
	if status >= 0 {
		filters["status"] = status
	}

	// 加盟商只能查看自己的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 查询优惠券列表
	coupons, total, err := models.GetCouponIssueList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券列表失败",
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取优惠券列表成功",
		"data": map[string]interface{}{
			"list":  coupons,
			"total": total,
		},
	}
	c.ServeJSON()
}

// BatchGet 批量获取优惠券信息
func (c *CouponController) BatchGet() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var ids []int64
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &ids)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 查询优惠券信息
	coupons := make([]*models.Coupon, 0)
	for _, id := range ids {
		coupon, err := models.GetCouponById(id)
		if err != nil || coupon == nil {
			continue
		}

		// 检查加盟商权限
		if permResult.Admin.FranchiseId > 0 && coupon.FranchiseId != permResult.Admin.FranchiseId {
			continue
		}

		coupons = append(coupons, coupon)
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取优惠券信息成功",
		"data":    coupons,
	}
	c.ServeJSON()
}
